package com.moodincode.taskcenter.script;

import com.alibaba.fastjson.JSONObject;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Locale;

/**
 * js ajax 请求
 * @author moodincode
 */
public class AjaxUtil {
    private static Logger log= LoggerFactory.getLogger(AjaxUtil.class);
    /**
     * js发起ajax请求
     * @param param 先用封装类接收结果
     */
    public static void ajax(Object param){
        if(param==null||!(param instanceof ScriptObjectMirror)){
            log.error("js脚本调用ajax请求入参格式错误,入参{}",param);
            throw new IllegalArgumentException("入参格式错误");
        }
        ScriptObjectMirror objectMirror = (ScriptObjectMirror) param;
        String jsonString = JSONObject.toJSONString(objectMirror);
        //转换对象
        AjaxParam ajaxParam = JSONObject.parseObject(jsonString, AjaxParam.class);
        if(ajaxParam==null|| !StringUtils.hasText(ajaxParam.getUrl())||!StringUtils.hasText(ajaxParam.getType())){
            log.error("js脚本调用ajax请求入参格式错误,入参{}",jsonString);
            throw new IllegalArgumentException("ajax请求参数错误");
        }
        HttpMethod method = HttpMethod.resolve(ajaxParam.getType().toUpperCase(Locale.ROOT));
        if(method==null){
            log.error("js脚本调用ajax请求方式错误,method={}",ajaxParam.getType());
            throw new IllegalArgumentException("ajax请求方式不支持"+ajaxParam.getType());
        }
        RestTemplate restTemplate=new RestTemplate();
        HttpHeaders headers =new HttpHeaders();
        if(StringUtils.hasText(ajaxParam.getDataType())){
            if("xml".equalsIgnoreCase(ajaxParam.getDataType())){
                headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE);
            }else if("json".equalsIgnoreCase(ajaxParam.getDataType())) {
                headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            }
        }
        //设置请求头
        if(!CollectionUtils.isEmpty(ajaxParam.getHeader())){
            ajaxParam.getHeader().entrySet().forEach(e->headers.add(e.getKey(),e.getValue()));
        }
        //设置请求体
        Object data=null;
        if(ajaxParam.getData()!=null){
            data=ajaxParam.getData();
        }
        //设置超时时间
        if(ajaxParam.getTimeout()!=null){
            HttpComponentsClientHttpRequestFactory rf = (HttpComponentsClientHttpRequestFactory)restTemplate.getRequestFactory();
            rf.setConnectTimeout(ajaxParam.getTimeout());
            rf.setReadTimeout(ajaxParam.getTimeout());
        }
        HttpEntity<Object>  httpEntity=new HttpEntity<>(data, headers);
        ResponseEntity<String> entity = restTemplate.exchange(ajaxParam.getUrl(), method, httpEntity, String.class);
        Response response=new Response();
        //补充请求头
        if(entity.getHeaders()!=null){
            response.setHeader(RequestDataUtil.parseHeaderParam(entity.getHeaders()));
        }
        response.setStatusCode(entity.getStatusCodeValue());
        response.setData(entity.getBody());
        //回调结果
        if(ajaxParam.getCallback()!=null){
            ScriptObjectMirror callback = (ScriptObjectMirror)objectMirror.getMember("callback");
            callback.call(callback,response);
        }
        //成功是回调
        if(ajaxParam.getSuccess()!=null&&response.getStatusCode()==HttpStatus.OK.value()){
            ScriptObjectMirror callback = (ScriptObjectMirror)objectMirror.getMember("success");
            callback.call(callback,response);
            //失败是回调结果
        }else if(ajaxParam.getError()!=null&&response.getStatusCode()!=HttpStatus.OK.value()){
            ScriptObjectMirror callback = (ScriptObjectMirror)objectMirror.getMember("error");
            callback.call(callback,response);
        }



    }
}
